package com.smoed.common.utilities;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.AssignableTypeFilter;

public final class FrameworkUtils {
    private FrameworkUtils() {
    }

    private static final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);

    public static <T> List<Class<T>> getImplementingClasses(String basePkg, Class<T> clas) {
        scanner.resetFilters(true);

        final List<Class<T>> classes = new ArrayList<Class<T>>();
        scanner.addIncludeFilter(new AssignableTypeFilter(clas));
        for (BeanDefinition bd : scanner.findCandidateComponents(basePkg)) {
            try {
                classes.add((Class<T>)Class.forName(bd.getBeanClassName()));
            } catch (ClassNotFoundException e) {
                e.printStackTrace(); // should be impossible for this to ever happen
            }
        }

        return classes;
    }

    public static <T extends Annotation> List<Class<T>> getClassesForAnnotation(String basePkg, Class<T> clas) {
        scanner.resetFilters(true);

        final List<Class<T>> classes = new ArrayList<Class<T>>();
        scanner.addIncludeFilter(new AnnotationTypeFilter(clas));
        for (BeanDefinition bd : scanner.findCandidateComponents(basePkg)) {
            try {
                classes.add((Class<T>)Class.forName(bd.getBeanClassName()));
            } catch (ClassNotFoundException e) {
                e.printStackTrace(); // should be impossible for this to ever happen
            }
        }

        return classes;
    }

    public static <A extends Annotation> A getAnnotationDefault(Class<A> annotation) {
        return (A) Proxy.newProxyInstance(annotation.getClassLoader(),
                new Class[] {annotation},
                new DefaultInvocationHandler());
    }

    private static class DefaultInvocationHandler implements InvocationHandler {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return method.getDefaultValue();
        }
    }
}
